package com.hunterai.service.impl;

import com.hunterai.dao.UserRepository;
import com.hunterai.dto.AuthResponse;
import com.hunterai.dto.LoginRequest;
import com.hunterai.dto.RegisterRequest;
import com.hunterai.dto.UserDTO;
import com.hunterai.entity.User;
import com.hunterai.security.JwtUtil;
import com.hunterai.service.AuthService;
import com.hunterai.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
public class AuthServiceImpl implements AuthService {

    private final UserRepository userRepository;
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private final AuthenticationManager authenticationManager;
    private final UserDetailsService userDetailsService;
    private final JwtUtil jwtUtil;

    @Autowired
    public AuthServiceImpl(UserRepository userRepository, 
                          UserService userService, 
                          PasswordEncoder passwordEncoder,
                          AuthenticationManager authenticationManager,
                          UserDetailsService userDetailsService,
                          JwtUtil jwtUtil) {
        this.userRepository = userRepository;
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
        this.jwtUtil = jwtUtil;
    }

    @Override
    public AuthResponse register(RegisterRequest request) {
        // 检查用户名是否存在
        if (userRepository.findByUserName(request.getUserName()).isPresent()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "用户名已存在");
        }
        // 检查邮箱是否已被使用
        if (request.getEmail() != null && !request.getEmail().isEmpty() &&
                userRepository.findByEmail(request.getEmail()).isPresent()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "邮箱已被使用");
        }
        // 检查手机号唯一
        if (request.getMobile() != null && !request.getMobile().isEmpty() &&
                userRepository.findByMobile(request.getMobile()).isPresent()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "手机号已被使用");
        }
        // 创建新用户
        User user = new User();
        user.setUserName(request.getUserName());
        user.setEmail(request.getEmail());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setCreatedAt(LocalDateTime.now());
        user.setLastLogin(LocalDateTime.now());
        user.setNickName(request.getNickName());
        user.setMobile(request.getMobile());
        if (request.getGender() != null) {
            try {
                user.setGender(User.Gender.valueOf(request.getGender().toUpperCase()));
            } catch (Exception e) {
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "性别参数非法");
            }
        }
        // 保存用户
        UserDTO savedUser = userService.save(user);
        // 生成JWT
        UserDetails userDetails = userDetailsService.loadUserByUsername(savedUser.getUserName());
        String token = jwtUtil.generateToken(userDetails, savedUser.getId());
        // 返回认证响应
        return new AuthResponse(token, savedUser);
    }

    @Override
    public AuthResponse login(LoginRequest request) {
        try {
            // 尝试认证
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(request.getUserName(), request.getPassword())
            );
        } catch (Exception e) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "用户名或密码错误");
        }

        // 获取用户信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(request.getUserName());
        Optional<User> userOptional = userRepository.findByUserName(request.getUserName());
        
        if (userOptional.isEmpty()) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "用户不存在");
        }
        
        User user = userOptional.get();

        // 更新最后登录时间
        user.setLastLogin(LocalDateTime.now());
        UserDTO updatedUser = userService.save(user);

        // 生成JWT
        String token = jwtUtil.generateToken(userDetails, updatedUser.getId());

        // 返回认证响应
        return new AuthResponse(token, updatedUser);
    }
}